package org.tangjl.cas.client.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public static final String SESSION_USER = "cas-app-user";

    /**
     * Default constructor. 
     */
    public LoginServlet() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String template = "进入cas-app\r\nsession:%s\r\n%s\r\n%s\r\n%s";
		String remoteUser = "RemoteUser:" + request.getRemoteUser();
		String userPrincipal = "UserPrincipal:" + request.getUserPrincipal().getName();

		HttpSession session = request.getSession();
		String sessionId = session.getId();
		if (session.getAttribute(LoginServlet.SESSION_USER) == null) {
			request.getSession().setAttribute(SESSION_USER, request.getRemoteUser());
		}
		String sessionUser = "SessionUser:" + session.getAttribute(SESSION_USER);
		response.getOutputStream().write(String.format(template, sessionId, remoteUser, userPrincipal, sessionUser).getBytes());
	}

}
